package com.example.usbfileutils

import android.content.Context
import android.os.Environment
import android.os.storage.StorageManager
import android.util.Log
import androidx.core.content.ContextCompat
import java.io.File


class USBFileManager private constructor() {

    private lateinit var mContext: Context
    private val fileCopyExecutors: FileCopyExecutors = FileCopyExecutors()
    private var usbFilePath: String? = null

    companion object {
        private val TAG = "USBFileManager"
        val instance = USBFileManager()
    }

    fun reset() {
    }

    fun init(context: Context) {
        mContext = context.applicationContext

        usbFilePath = findAvaliableUSBPath()

        Log.d(TAG, "init find usbFilePath: $usbFilePath")
    }


    private fun findAvaliableUSBPath(): String? {
        val externalFilesDirs = ContextCompat.getExternalFilesDirs(mContext, null)
        for (file in externalFilesDirs) {
            Log.i(TAG, "find path:" + file.absolutePath)
//            if (file != null && file.exists() && !file.absolutePath.startsWith(Environment.getExternalStorageDirectory().absolutePath)) {
//                return file.absolutePath
//            }
            return file.absolutePath
        }
        return null
    }


    /**
     * Copy files to the USB Devices
     */
    fun copyFilesToUSB(srcFilePath: File, listener: Listener): Int {

        if (usbFilePath == null) {
            Log.e(TAG, "root file path is null")
            return -1
        }

        Log.d(TAG, "start copy files to USB")

        copyFiles(srcFilePath, File(usbFilePath!!))

        fileCopyExecutors.start(object : FileCopyExecutors.Listener {
            override fun onStart() {
                listener.onStart()
            }

            override fun onComplete() {
                listener.onComplete()
            }
        })

        return 0
    }

    private fun copyFiles(srcFilePath: File, currentDestFilePath: File) {

        val destFile = File(currentDestFilePath, srcFilePath.name)

        if (srcFilePath.isDirectory) {

            if (!destFile.exists()) {
                destFile.mkdir()
            }

            val listFiles = srcFilePath.listFiles()

            Log.d(TAG, "$srcFilePath has file length ${listFiles?.size}")

            listFiles?.forEach {
                copyFiles(it, destFile)
            }

        } else {
            Log.d(TAG, "copy $srcFilePath to the Usb device")
            fileCopyExecutors.addTask(FileCopyTask(srcFilePath, destFile))
        }
    }

    fun fetchUsbFileList(dirName: String): Array<File>? {
        if (usbFilePath == null) {
            Log.e(TAG, "root file path is null")
            return null
        }

        val tmpFile = File("/mnt/media_rw/AAEF-F30D/MiCam/RaceClips")

        if (tmpFile.exists()) {
            Log.d(TAG, "${tmpFile.name} exists")
        } else {
            Log.d(TAG, "${tmpFile.name} does not exists")
        }

        val file = File(File(usbFilePath!!), dirName)

        return file.listFiles()
    }

    fun destroy() {
        fileCopyExecutors.stop()
    }

    interface Listener {
        fun onStart()
        fun onComplete()
    }
}